import React, { useState, useEffect } from 'react';
import { connect, useDispatch } from 'umi';
import { Drawer, Form, Button, Input, Select, message, Radio } from 'antd';
import debounce from 'lodash/debounce';
import SearchInput from '@/components/SearchInput';
import { MOBILE_REG, EMAIL_REG, PWD_REG } from '@/utils/const';

const { Option } = Select;
const layout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 18 },
};

const UserAddEdit = (props) => {
  const { drawerType, handleClose, editData, allRoleList, appCode } = props;
  const [employeeSelectList, setEmployeeSelectList] = useState([]);
  const [form] = Form.useForm();
  const dispatch = useDispatch();

  const getEmployeeList = (employeeCode) => {
    dispatch({
      type: 'userManageModel/getEmployeeList',
      payload: {
        pageIndex: 1,
        pageSize: 50,
        employeeCode,
      },
    }).then((res) => {
      const { code, data, message: errMsg } = res;
      if (code === 0) {
        const { dataList } = data;
        setEmployeeSelectList(dataList);
      } else {
        message.error(errMsg);
      }
    });
  };

  useEffect(() => {
    getEmployeeList();
  }, []);

  const handleSubmit = () => {
    const { validateFields } = form;
    validateFields().then((values) => {
      const { userAccount, ...rest } = values;
      const params = { ...rest };
      if (drawerType !== 'add') {
        params.id = editData.id;
      }
      if (userAccount !== editData.userAccount) {
        params.userAccount = userAccount;
      }
      if (drawerType !== 'updateUser') {
        params.appCode = appCode;
      }
      dispatch({
        type: `userManageModel/${drawerType === 'add' ? 'addUser' : 'updateUser'}`,
        payload: params,
      }).then((res) => {
        const { code, message: errMsg } = res;
        if (code === 0) {
          message.success(`${drawerType === 'add' ? '新增' : '编辑'}成功`);
          handleClose(true);
        } else {
          message.error(errMsg);
        }
      });
    });
  };

  const handleRoleSelectSearch = debounce(getEmployeeList, 300);

  const handleFormValuesChange = (changedValues) => {
    const { employeeCode } = changedValues;
    if (employeeCode) {
      const curSelectData = employeeSelectList.filter(item => item.employeeCode === employeeCode);
      if (curSelectData?.length > 0) {
        const [{ email, mobilePhone, id, employeeName, orgAndPositionList }] = curSelectData;
        form.setFieldsValue({
          employeeId: id,
          userName: employeeName,
          email,
          mobilePhone,
          orgs:
            orgAndPositionList?.length > 0
              ? orgAndPositionList.map(item => item.orgName).join(',')
              : '',
        });
      }
    }
  };

  return (
    <Drawer
      title={`${drawerType === 'add' ? '添加' : '修改'}用户`}
      width={600}
      visible
      onClose={handleClose}
      bodyStyle={{ paddingBottom: 80 }}
      footer={(
        <div style={{ textAlign: 'right' }}>
          <Button onClick={handleClose} style={{ marginRight: 8 }}>
            {' '}
            取消
          </Button>
          <Button type="primary" onClick={handleSubmit}>
            {drawerType === 'add' ? '添加' : '保存'}
          </Button>
        </div>
      )}
    >
      <Form {...layout} form={form} onValuesChange={handleFormValuesChange}>
        <Form.Item
          name="userAccount"
          label="用户账号"
          rules={[
            { required: true },
            { pattern: /^[0-9a-zA-Z_]{4,25}$/, message: '用户账号格式不正确，请重新输入' },
          ]}
          initialValue={editData.userAccount}
        >
          <Input placeholder="4-25位字符，由字母、数字、下划线组成，字母不区分大小写" />
        </Form.Item>
        <Form.Item name="employeeId" style={{ display: 'none' }}>
          <Input />
        </Form.Item>
        <Form.Item name="employeeCode" label="员工工号" initialValue={editData.employeeCode}>
          <SearchInput
            data={employeeSelectList}
            optionValueKey="employeeCode"
            optionTextKey={['employeeCode', 'employeeName']}
            handleSearch={handleRoleSelectSearch}
            // handleChange={handleRoleSelectChange}
            placeholder="请选择员工，输入员工工号搜索"
            optionLabelProp="key"
          />
        </Form.Item>
        <Form.Item
          label="姓名"
          name="userName"
          initialValue={editData.userName}
          rules={[
            { required: true, message: '请输入姓名' },
            {
              pattern: /^([\u4e00-\u9fa5]|[a-zA-Z0-9]|-|_|@|#){1,10}$/,
              message: '请输入1-10位中英文、数字、常用字符(-_@#)',
            },
          ]}
        >
          <Input placeholder="请输入1-10位中英文、数字、常用字符" />
        </Form.Item>
        {drawerType === 'add' && (
          <Form.Item
            name="passwd"
            label="密码"
            initialValue={editData.passwd}
            rules={[
              { required: true },
              {
                pattern: PWD_REG,
                message: '密码格式不正确，请重新输入',
              },
            ]}
          >
            <Input.Password placeholder="至少8位，由数字、字母或特殊字符中2种方式组成" />
          </Form.Item>
        )}
        <Form.Item name="orgs" label="组织机构" initialValue={editData.orgs}>
          <Input placeholder="组织机构" readOnly disabled />
        </Form.Item>
        <Form.Item
          name="roleIdList"
          label="角色"
          initialValue={editData.roleList ? editData.roleList.map(item => item.roleId) : []}
          rules={[{ required: true, message: '请选择角色' }]}
        >
          <Select
            mode="multiple"
            showSearch
            placeholder="请选择角色"
            filterOption={(input, option) =>
              option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
          >
            {allRoleList.map(item => (
              <Option key={item.roleId} value={item.roleId}>
                {item.roleName}
              </Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item
          name="mobilePhone"
          label="手机号"
          initialValue={editData.mobilePhone}
          rules={[{ pattern: MOBILE_REG, message: '请输入正确的手机号' }]}
        >
          <Input placeholder="请输入手机号" />
        </Form.Item>
        <Form.Item
          name="email"
          label="邮箱"
          initialValue={editData.email}
          rules={[{ pattern: EMAIL_REG, message: '请输入正确的邮箱' }]}
        >
          <Input placeholder="请输入邮箱" />
        </Form.Item>
        <Form.Item
          name="userState"
          label="用户状态"
          initialValue={typeof editData.userState === 'undefined' ? 1 : editData.userState}
        >
          <Radio.Group>
            <Radio value={1}>激活</Radio>
            <Radio value={0}>未激活</Radio>
          </Radio.Group>
        </Form.Item>
      </Form>
    </Drawer>
  );
};

export default connect(state => state)(UserAddEdit);
